<?php
/**
 * Created by PhpStorm.
 * User: lance
 * Date: 15/03/2018
 * Time: 9:41 AM
 */

namespace app\manager\admin;


use app\admin\controller\Admin;
use think\Db;
use app\common\builder\ZBuilder;
use php_excel\libs\Excel;

class Export extends Admin
{
    //显示筛选页面
    public function export()
    {
        //部门
        $a_departments = Db::name('manager')->distinct(true)->column('department');
        //以部门名作为键名
        $a_departments = array_combine($a_departments,$a_departments);

        //网点
        $a_nets = Db::name('netsite_record')->column('net_name');
        //以网点名作为键名
        $a_nets = array_combine($a_nets,$a_nets);

        return ZBuilder::make("form")
            ->addFormItems([
                ['select', 'department', '部门', '', $a_departments],
                ['radio', 'sex', '性别', '', [1 => '全部', 2 => '男', 3 => '女'], 1],
                ['select', 'net_name', '所属网点', '', $a_nets ],
            ])
            ->method('get')
            ->isAjax(false)
            ->setUrl(url('doExport'))
            ->fetch();
    }

    //进行导出
    public function doExport()
    {
        /*step1 获取筛选条件*/
        $a_where = [];
        //部门
        if (input("?get.department")):
            $s_department = input("get.department/s");
            if (!empty($s_department)):
                $a_where['department'] = $s_department;
            endif;
        endif;

        //性别
        if (input("?get.sex") && input('get.sex/d') !== 1 && in_array(input('get.sex/d'), [2, 3])):
            $a_sex = [
                2 => '男',
                3 => '女'
            ];
            $a_where['sex'] = $a_sex[input('get.sex/d')];
        endif;

        //所属网
        if (input("?get.net_name")):
            //网点名称
            $s_netName = input('get.net_name/s');
            if (!empty($s_netName)):
                $a_where['net_name'] = $s_netName;
            endif;
        endif;

        /*step2 根据筛选条件查询客户数据*/
        $a_managers = Db::name('manager')
            ->where($a_where)
            ->field(['id','type','birth_time'],true)
            ->select();
        /*step3 利用excel类进行导出*/
        if (!empty($a_managers)):
            $a_managers = array_map(function ($a_item) {
                return array_values($a_item);
            }, $a_managers);
            $o_excel = new Excel();
            //长度
            $i_len = count($a_managers[0]);
            $a_letters = range('A', chr(ord('A') + $i_len - 1));
            $a_headers = ['部门','姓名','柜员号','身份证号','性别','电话','办公电话','电子邮箱','网点'];
            $o_excel->export($a_letters, $a_headers, $a_managers, '客户经理资料导出' . uniqid());
            exit;
        else:

                $this->error("无符合条件的客户经理资料");
        endif;
    }
}